package org.zpmis.api.business;

import cn.hutool.core.lang.UUID;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.customer.enums.CustomerPlanEnum;
import org.zpmis.domain.customer.enums.IntentionEnum;
import org.zpmis.domain.customer.enums.ReturnVisitEnum;
import org.zpmis.domain.customer.model.CustomerPlan;
import org.zpmis.domain.customer.model.Intention;
import org.zpmis.domain.customer.model.ReturnVisit;
import org.zpmis.domain.customer.qo.AddIntentionQo;
import org.zpmis.domain.customer.qo.IntentionListQo;
import org.zpmis.domain.customer.qo.IntentionTrackQo;
import org.zpmis.domain.customer.service.CustomerPlanService;
import org.zpmis.domain.customer.service.IntentionService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.zpmis.domain.customer.service.ReturnVisitService;
import org.zpmis.domain.customer.vo.IntentionListVo;
import org.zpmis.domain.customer.vo.IntentionTrackVo;
import org.zpmis.domain.role.vo.SysMenuListVo;
import org.zpmis.domain.user.service.WxApiService;
import org.zpmis.domain.wechat.service.WxAuthMpService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-2
 * Time: 14:48:50
 */
@Service
@Slf4j
public class IntentionWebService {
     @Reference
     private IntentionService intentionService;

     @Reference
     private ReturnVisitService returnVisitService;

     @Reference
     private CustomerPlanService customerPlanService;

     @Reference
     private WxAuthMpService wxAuthMpService;

     public void addIntention(AddIntentionQo addIntentionQo) throws Exception{
          String code = addIntentionQo.getCode();
          String openId = "";
          if(StringUtils.isNotBlank(code)){
               String msg = wxAuthMpService.getOpenIdByCode(code);
               if(!msg.equals("error")){
                    openId = msg;
               }
          }
          intentionService.save(
               Intention.builder()
                       .name(addIntentionQo.getCompanyName())
                       .customerSource(addIntentionQo.getCustomerSource())
                       .intentionDescript(addIntentionQo.getIntentionDescript())
                       .contactMobile(addIntentionQo.getContactMobile())
                       .contactPerson(addIntentionQo.getContactPerson())
                       .openId(openId)
                       .createTime(Instant.now().toEpochMilli())
                       .updateTime(Instant.now().toEpochMilli())
                       .isDeleted(IntentionEnum.NOT_DELETE.code())
                       .status(IntentionEnum.DISABLE_STATUS.code())
                       .companyCode(UUID.randomUUID().toString().replaceAll("-",""))
                       .build());
     }


     public PageInfo intentionList(IntentionListQo intentionListQo) throws Exception{

          Condition condition = new Condition(Intention.class);
          Example.Criteria criteria = condition.createCriteria();
          criteria.andEqualTo("isDeleted",IntentionEnum.NOT_DELETE.code());
          if(StringUtil.isNotEmpty(intentionListQo.getName())){
               criteria.andLike("name","%"+intentionListQo.getName()+"%");
          }
          if(StringUtil.isNotEmpty(intentionListQo.getContactMobile())){
               criteria.andLike("contactMobile","%"+intentionListQo.getContactMobile()+"%");
          }
          if(StringUtil.isNotEmpty(intentionListQo.getContactPerson())){
               criteria.andLike("contactPerson","%"+intentionListQo.getContactPerson()+"%");
          }
          if(intentionListQo.getStatus() != null){
               criteria.andEqualTo("status",intentionListQo.getStatus());
          }
          if(intentionListQo.getStartTime() != null && intentionListQo.getEndTime() != null){
               criteria.andGreaterThanOrEqualTo("createTime",intentionListQo.getStartTime());
               criteria.andLessThanOrEqualTo("createTime",intentionListQo.getEndTime());
          }
          if(intentionListQo.getStartTime() == null && intentionListQo.getEndTime() != null){
               criteria.andLessThanOrEqualTo("createTime",intentionListQo.getEndTime());
          }
          if(intentionListQo.getStartTime() != null && intentionListQo.getEndTime() == null){
               criteria.andGreaterThanOrEqualTo("createTime",intentionListQo.getStartTime());
               criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
          }
          if(intentionListQo.getCustomerSource() != null){
               criteria.andEqualTo("customerSource",intentionListQo.getCustomerSource());
          }
          condition.orderBy("createTime").desc();
          PageHelper.startPage(intentionListQo.getPageNum(),intentionListQo.getPageSize());
          List<Intention> intentionList = intentionService.findByCondition(condition);
          PageInfo pageInfo = new PageInfo<>(intentionList);
          //设置返回自定义的对象集合
          List<IntentionListVo> resultList = intentionList.stream().map(IntentionListVo::new).collect(Collectors.toList());
          pageInfo.setList(resultList);
          return pageInfo;
     }

     /**
      * 意向轨迹集合查询
      * @param intentionTrackQo
      * @return
      * @throws BusinessException
      * @throws Exception
      */
     public List<IntentionTrackVo> intentionTrack(IntentionTrackQo intentionTrackQo) throws BusinessException,Exception{
          Long id = intentionTrackQo.getId();
          Intention intention = intentionService.findById(id);
          if(intention == null){
               throw new BusinessException(ResultCode.DATA_NOT_FOUND);
          }
          //查询回访集合
          Condition returnVisitCondition = new Condition(ReturnVisit.class);
          returnVisitCondition.createCriteria()
                  .andEqualTo("isDeleted", ReturnVisitEnum.NOT_DELETE.code())
                  .andEqualTo("intentionId",id);
          List<ReturnVisit> returnVisitList = returnVisitService.findByCondition(returnVisitCondition);
          List<IntentionTrackVo> visitTrackVoList = returnVisitList.stream().map(IntentionTrackVo::new).collect(Collectors.toList());
          //查询计划集合
          Condition customerPlanCondition = new Condition(CustomerPlan.class);
          customerPlanCondition.createCriteria()
                  .andEqualTo("isDeleted", CustomerPlanEnum.NOT_DELETE.code())
                  .andEqualTo("intentionId",id);
          List<CustomerPlan> customerPlanList = customerPlanService.findByCondition(customerPlanCondition);
          List<IntentionTrackVo> planTrackVoList = customerPlanList.stream().map(IntentionTrackVo::new).collect(Collectors.toList());
          List<IntentionTrackVo> resultTrackVoList = new ArrayList<>();
          resultTrackVoList.addAll(visitTrackVoList);
          resultTrackVoList.addAll(planTrackVoList);
          //按照时间排序
          List<IntentionTrackVo> sortedList = resultTrackVoList.stream().sorted(Comparator.comparing(IntentionTrackVo::getVisitTime, Comparator.nullsFirst(Long::compareTo))).collect(Collectors.toList());

          return sortedList;
     }
}
